package com.example.demos.web.controller;


import com.example.demos.entity.Dep;
import com.example.demos.service.DepService;
import com.example.demos.util.PageBean;
import com.example.demos.util.PageParam;
import com.example.demos.util.Result;
import com.example.demos.util.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.List;

@RestController
@RequestMapping("/v2/dep")
public class DepController {

    @Autowired
    private DepService depService;

    @GetMapping("/listByPage")
    public Result<PageBean<List<Dep>>> select(PageParam pageParam, Dep dep) {
        PageBean<List<Dep>> select = depService.select(pageParam, dep);
        return Result.ok(select);
    }

    @GetMapping("/selectone")
    public Result<Dep> selectById(BigInteger id) {
        Dep dep = depService.selectById(id);
        return Result.ok(dep);
    }

    @PostMapping("/add")
    public Result<Void> insert(Dep dep) {
        if (dep.getName() == "" || dep.getTele() == "") {
            return Result.bizErr("姓名或电话不能为空");
        }
        if (!Validator.isValidTele(dep.getTele())) {
            return Result.bizErr("电话格式不正确");
        }
        int insert = depService.insert(dep);
        if (insert > 0) {
            return Result.ok("部门新增成功");
        } else if (insert == -1) {
            return Result.bizErr("部门名不能重复");
        } else {
            return Result.bizErr("部门新增失败");
        }

    }

    @PostMapping("/update")
    public Result<Void> update(Dep dep) {
        if (!Validator.isValidTele(dep.getTele())) {
            return Result.bizErr("电话格式不正确");
        }
        int update = depService.update(dep);
        if (update > 0) {
            return Result.ok("部门修改成功");
        } else if (update == -1) {
            return Result.bizErr("部门名不能重复");
        } else {
            return Result.bizErr("部门新增失败");
        }
    }

    @DeleteMapping
    public Result<Void> delete(BigInteger id) {
        int delete = depService.delete(id);
        if (delete > 0) {
            return Result.ok("部门删除成功");
        } else if (delete == -1) {
            return Result.bizErr("部门内还有员工，不能删除");
        } else {
            return Result.bizErr("部们删除失败");
        }
    }

}
